#!/usr/bin/python3
# coding=utf-8
#
# Copyright (C) 2025.
# Huawei Technologies Co., Ltd. All rights reserved.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# ===============================================================================

import sys
import numpy as np

# 支持的数据类型映射
dtype_map = {
    "fp32": np.float32,
    "fp16": np.float16,
}

# 容差设置 fp32
relative_tol = 1e-3
absolute_tol = 1e-5
error_tol = 1e-3
# 容差设置 fp16
# relative_tol = 5e-3
# absolute_tol = 1e-3
# error_tol = 2e-3 

# 默认数据类型（可改成 "fp16" 或 "bf16"）
data_type = dtype_map["fp32"]


def verify_result(output_file, golden_file):
    """读取二进制文件并进行比对"""
    output = np.fromfile(output_file, dtype=data_type).reshape(-1)
    golden = np.fromfile(golden_file, dtype=data_type).reshape(-1)

    different_element_results = np.isclose(
        output,
        golden,
        rtol=relative_tol,
        atol=absolute_tol,
        equal_nan=True
    )
    different_element_indexes = np.where(different_element_results == False)[0]

    for index, real_index in enumerate(different_element_indexes):
        golden_data = golden[real_index]
        output_data = output[real_index]
        denom = golden_data if golden_data != 0 else 1.0
        print(
            "data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f" %
            (real_index, golden_data, output_data,
             abs(output_data - golden_data) / abs(denom))
        )
        if index == 30:  # 最多打印 30 个
            break

    error_ratio = float(different_element_indexes.size) / golden.size
    print("error ratio: %.4f, tolerance: %.4f" % (error_ratio, error_tol))
    return error_ratio <= error_tol


if __name__ == '__main__':
    try:
        if len(sys.argv) != 3:
            print("Usage: python3 verify_lp_norm_v2.py <output.bin> <golden.bin>")
            sys.exit(1)

        res = verify_result(sys.argv[1], sys.argv[2])
        if not res:
            raise ValueError("[ERROR] result error")
        else:
            print("✅ test pass")
    except Exception as e:
        print(e)
        sys.exit(1)
